<?php
session_id($_REQUEST['sessionId']);
session_start();
if (!isset($_SESSION["USUARIO"])) {
    return;
}
include_once "opendb.php";
$uid = $_SESSION["USUARIO"];
$comentarios = $_REQUEST["comentarios"];
$contenidoId = $_REQUEST["contenidoId"];
$file_temp = $_FILES['file']['tmp_name'];
$file_name = $_FILES['file']['name'];
$file_path = $_SERVER['DOCUMENT_ROOT'].$imgdir;
$thumb_path = $_SERVER['DOCUMENT_ROOT'].$thumbdir;
$can_go = true;

$query = "SELECT ca.admin as ca_admin, ca.ownerid as ca_ownerid, co.admin as co_admin, co.ownerid as co_ownerid FROM categorias ca, contenido co WHERE co.categoriaid = ca.id AND co.id = $contenidoId";
$result = mysql_query($query);
if ($row = mysql_fetch_assoc($result)) {
	if ($row['co_admin'] == true || $row['ca_admin'] == true) {
		if ($row['co_admin'] == true && $row['ca_admin'] == true) {
			if ($row['co_ownerid'] !== $uid && $row['ca_ownerid'] !== $uid) {
				$can_go = false;
			}
		} else if ($row['co_admin'] == true && $row['ca_admin'] == false) {
            if ($row['co_ownerid'] !== $uid) {
                $can_go = false;
            }
		}  else if ($row['co_admin'] == false && $row['ca_admin'] == true) {
            if ($row['ca_ownerid'] !== $uid) {
                $can_go = false;
            }
		}
	}
}
mysql_free_result($result);

if ($can_go == false) {
?>
<datos>
    <error>El acceso es privado</error>
</datos>
<?php
    //TODO: Falta remover el $file_temp
    mysql_close($conn);
    return;
}

$archivoId = 0;
$query  = "SELECT id FROM archivos WHERE nombre = '$file_name' AND contenidoid = $contenidoId";
$result = mysql_query($query);
if ($row = mysql_fetch_assoc($result)) {
	$archivoId = $row['id'];
    mysql_free_result($result);
} else {
	mysql_free_result($result);
	$query = "INSERT INTO archivos (nombre, fecalta, contenidoid) VALUES ('$file_name', now(), $contenidoId)";
	$exec = true;
	mysql_query($query) or $exec = false;
	if ($exec = true) {
	    $archivoId = mysql_insert_id();
	}
}

if ($archivoId !== 0) {
	$major = 0;
	$minor = 0;
	
	$query  = "SELECT major, minor FROM versiones WHERE archivoid = $archivoId ORDER BY major DESC, minor DESC LIMIT 1";
	$result = mysql_query($query);
    if ($row = mysql_fetch_assoc($result)) {
        $major = $row['major'];
        $minor = $row['minor'];
	   
        if ($major == null) {
            $major = 0;
        }
        if ($minor == null) {
        	$minor = 0;
        } else {
        	$minor = $minor + 1;
        }
	}
	mysql_free_result($result);
	
	$query = "INSERT INTO versiones (major, minor, fecalta, usuarioid, archivoid, comentarios, eliminado) VALUES ($major, $minor, now(), $uid, $archivoId, '$comentarios', 0)";
    $exec = true;
    mysql_query($query) or $exec = false;
    if ($exec == true) {
        $versionId = mysql_insert_id();
        
        move_uploaded_file($file_temp,"$file_path/$versionId");
        $file_temp = "$file_path/$versionId";
        
        $query  = "UPDATE archivos SET versionid = $versionId WHERE id = $archivoId";
        mysql_query($query) or $exec = false;
        
        try {
	        $img_thumb = 0;
	        if(preg_match('/[.](jpg|jpeg)$/', strtolower($file_name))) {
	        	$img_thumb = imagecreatefromjpeg($file_temp) or $img_thumb = 0;
	        } else if (preg_match('/[.](gif)$/', strtolower($file_name))) {
	            $img_thumb = imagecreatefromgif($file_temp) or $img_thumb = 0;
	        } else if (preg_match('/[.](png)$/', strtolower($file_name))) {
	        	$img_thumb = imagecreatefrompng($file_temp) or $img_thumb = 0;
	        } else if (preg_match('/[.](gd2)$/', strtolower($file_name))) {
	        	$img_thumb = imagecreatefromgd2($file_temp) or $img_thumb = 0;
	        } else if (preg_match('/[.](gd)$/', strtolower($file_name))) {
	            $img_thumb = imagecreatefromgd($file_temp) or $img_thumb = 0;
	        } else if (preg_match('/[.](bmp)$/', strtolower($file_name))) {
	            $img_thumb = imagecreatefromwbmp($file_temp) or $img_thumb = 0;
	        } else if (preg_match('/[.](xbm)$/', strtolower($file_name))) {
	            $img_thumb = imagecreatefromxbm($file_temp) or $img_thumb = 0;
	        } else if (preg_match('/[.](xpm)$/', strtolower($file_name))) {
	            $img_thumb = imagecreatefromxpm($file_temp) or $img_thumb = 0;
	        }
	        if ($img_thumb !== 0) {
	        	$ox = imagesx($img_thumb);
	        	$oy = imagesy($img_thumb);
	        	
	        	if ($ox > $oy) {
		        	$nx = 200;
		        	$ny = floor($oy * (200 / $ox));
	        	} else {
	                $ny = 200;
	                $nx = floor($ox * (200 / $oy));
	        	}
	        	
	        	$nm = imagecreatetruecolor($nx, $ny);
	        	
	        	imagecopyresized($nm, $img_thumb, 0, 0, 0, 0, $nx, $ny, $ox, $oy);
	        	
	        	imagejpeg($nm, "$thumb_path/$versionId");
	        	
	        	imagedestroy($img_thumb);
	        	imagedestroy($nm);
	        }
        } catch (Exception $e) {
        	// Ignorar        
        }
?>
<datos>
    <exito>Upload completo</exito>
</datos>
<?php
    } else {
?>
<datos>
    <error>No se pudo subir a internet</error>
</datos>
<?php
    }
} else {
?>
<datos>
    <error>No se pudo subir a internet</error>
</datos>
<?php
}
mysql_close($conn);
?>